<?php
/**
 * Cookie class
 *
 */
class Cookie
{
    protected $name;
    protected $expire;
    protected $domain;
    protected $path;
    protected $valuesSeparator = '.';
    protected $values = array();

    protected $isPresent = false;

    public function __construct( $name, $expire = null, $domain = '', $path = '/' )
    {
        $this->name = $name;

        if (empty($expire) || !is_numeric($expire) || $expire < 0)
        {
            $this->expire = 0;
        }
        else
        {
            $this->expire = $expire;
        }

        $this->domain = $domain;
        $this->path = $path;

        $cookie = Request::GetCookie($this->name);
        if (!empty($cookie))
        {
            $this->LoadCookieValues($cookie);
            $this->isPresent = true;
        }
    }

    public function IsPresent()
    {
        return $this->isPresent;
    }

    public function GetValue($key = 0, $defaultValue = null)
    {
        return isset($this->values[$key]) ? $this->values[$key] : $defaultValue;
    }

    public function SetValue($value = '', $key = 0)
    {
        $this->values[$key] = $value;
    }

    public function Save()
    {
        $this->Set( $this->name, $this->GenerateStringValue(), $this->expire, true, $this->path, $this->domain );
    }

    /**
     * Sets a cookie.
     *
     * @param string $name      Name for the cookie
     * @param string $value     Value for the cookie
     * @param int    $expire    Cookie expiration period
     * @param bool   $raw       True to not urlencode value
     * @param string $path      Path
     * @param string $domain    Domain name
     * @param bool   $secure    If secure
     * @param bool   $httponly  If uses only HTTP
     *
     * @return bool True if successfully set
     */
    protected function Set($name, $value, $expire = 0, $raw = true, $path = '/', $domain = '', $secure = false, $httponly = false)
    {
        if ($raw)
        {
            return setrawcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
        }

        return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
    }

    protected function LoadCookieValues( $cookie )
    {
        $this->values = explode($this->valuesSeparator, $cookie);
    }

    protected function GenerateStringValue()
    {
        return implode($this->valuesSeparator, $this->values);
    }
}
?>